//
//  ZJSelectView.m
//  Day2-蝉游记
//
//  Created by qianfeng on 15/11/17.
//  Copyright (c) 2015年 QianFeng. All rights reserved.
//

#import "ZJSelectView.h"
#import "ViewController.h"
@implementation ZJSelectView
{
    UIView * _bgView;
    UIView * _slideView;
    NSMutableArray * _buttons;
}

-(id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        [self initDataSource];
        [self addUI];
    }
    return self;
}
-(void)initDataSource{
    if(_buttons==nil){
        _buttons=[[NSMutableArray alloc]init];
    }
}
-(void)addUI{
    _bgView=[[UIView alloc]initWithFrame:CGRectMake(2,2, self.frame.size.width-4, self.frame.size.height-4)];
    _bgView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    _bgView.layer.masksToBounds=YES;
    _bgView.layer.cornerRadius=4;
    [self addSubview:_bgView];
    
    
    _slideView=[[UIView alloc]init];
    _slideView.backgroundColor=[UIColor whiteColor];
    _slideView.layer.masksToBounds=YES;
    _slideView.layer.cornerRadius=4;
    [_bgView addSubview:_slideView];
}

-(void)setTitles:(NSArray *)titles{
    CGFloat width=(_bgView.frame.size.width)/titles.count;
    CGFloat height=_bgView.frame.size.height-2;
    _slideView.frame=CGRectMake(1,1, width, height);
    for(int i=0;i<titles.count;i++){
        UIButton * button=[[UIButton alloc]initWithFrame:CGRectMake(i*width, 0, width, height)];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            button.selected=YES;
        }else{
            button.selected=NO;
        }
        button.tag=10+i;
        [_bgView addSubview:button];
        [_buttons addObject:button];
        
    }
    
}
-(void)buttonClicked:(UIButton *)button{
    NSInteger index =button.tag-10;
    for (UIButton * but in _buttons) {
        if (button==but) {
            but.selected=YES;
        }else{
            but.selected=NO;
        }
    }
   [UIView animateWithDuration:0.3 animations:^{
    _slideView.frame=CGRectMake(1+_slideView.frame.size.width * index,1, _slideView.frame.size.width, _slideView.frame.size.height);
   }];
    
    if(self.selectAtIndex){
        _selectAtIndex(index);
    }
}
-(void)loadWithIndex:(CGFloat)index{
    [UIView animateWithDuration:0.5 animations:^{
        _slideView.frame=CGRectMake(1+_slideView.frame.size.width * index,1, _slideView.frame.size.width, _slideView.frame.size.height);
    }];
    NSInteger k=index/1;
    for (int i=0; i<_buttons.count; i++) {
        UIButton * button=_buttons[i];
        if(k==i){
            button.selected=YES;
        }else{
            button.selected=NO;
        }
    }
    
    
    
}

@end
